using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using CHEnhanceEfCore.Extension;
using Microsoft.AspNetCore.Http;

namespace CHEnhanceEfCore.Common.Page
{
    public static class ContextUtil
    {
        private static readonly ThreadLocal<HttpContext> currentContext = new();

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="context"></param>
        public static void setValue(HttpContext context) => currentContext.Value = context;

        public static HttpContext getValue() => currentContext.Value;

        public static void clear() => currentContext.Value = null;

        /// <summary>
        /// 分页
        /// todo 无任何条件 后续进行优化
        /// </summary>
        /// <param name="enumerable"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Page<T> page<T>([NotNull] this IEnumerable<T> enumerable)
        {
            var context = currentContext.Value;
            var ree = context.Request;
            string page = ree.Query["page"];
            string pageSize = ree.Query["pageSize"];
            if (page.isNull() || pageSize.isNull())
            {
                return null;
            }

            List<T> dataList = enumerable.ToList();
            Page<T> result = new Page<T>
            {
                pageNum = Convert.ToInt32(page),
                pageSize = Convert.ToInt32(pageSize),
                total = dataList.Count,
                records = dataList
            };
            result.page();
            return result;
        }
    }
}